package com.thrd.basicframework.http.callback;

import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.thrd.basicframework.http.OkHttpBean;
import com.thrd.basicframework.http.utils.NoDataExceptions;
import com.tencent.mmkv.MMKV;

import java.io.IOException;
import java.net.ConnectException;

import okhttp3.Call;
import okhttp3.Response;

import static com.thrd.basicframework.http.utils.StatusCode.NO_DATA;
import static com.thrd.basicframework.http.utils.StatusCode.NO_INTERNET;
import static com.thrd.basicframework.http.utils.StatusCode.NO_SERVICE_ERROR;

public abstract class ThrdCallBack<T> extends Callback<T> {
    public static final int SUCCESS_CODE=200;
    @Override
    public T parseNetworkResponse(Response response, int id) throws Exception {
        // String json = response.body().string();
        if(response!=null){     //判断为空
            if (response.code()==SUCCESS_CODE) {     //请求正确
                String json = response.body().string();
                if (!TextUtils.isEmpty(json)) {
//                    onWriteLocal(response.request().url().toString(),json);
                    OkHttpBean okHttpBean=null;
                    okHttpBean   = JSON.parseObject(json, OkHttpBean.class);
                    //判断自定义状态码
                    if(SUCCESS_CODE==okHttpBean.getCode()){
                        onWriteLocal(response.request().url().toString(),okHttpBean.getData());
                        T t=onJson(okHttpBean.getData());
                        return t;
                    }

                }
                //数据为空
                throw new NoDataExceptions();

            }else {
                throw new NullPointerException("系统验证码错误");
            }
        }else{      //请求错误，未知异常
            throw new NullPointerException("Response==null");
        }

    }

    @Override
    public String onReadLocal(String key) {
        if(!TextUtils.isEmpty(key)){
            return   MMKV.defaultMMKV().decodeString(key);
        }
        return null;
    }

    @Override
    public void onWriteLocal(String key, String json) {
        if(!TextUtils.isEmpty(key)){
            MMKV.defaultMMKV().encode(key,json);
        }
    }

    @Override
    public void onError(Call call, Exception e, int id) {
        //没有网络
//        if(e instanceof ConnectException){
////            onFailed(e.getMessage(),NO_INTERNET);
//        }else


        if(e instanceof ConnectException){
            //没有网络
            onFailed(e.getMessage(),NO_INTERNET);
        }else if(e instanceof IOException){
            //服务器异常
            onFailed(e.getMessage(),NO_SERVICE_ERROR);
        }else{
            //没有数据
            onFailed(e.getMessage(),NO_DATA);
        }
    }

    public abstract void onFailed(String e, int code);

    //    public abstract T onJson(String s);




}
